import json
import re
from django.contrib.auth import login
from django.shortcuts import render

# Create your views here.
from QQLoginTool.QQtool import OAuthQQ

from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from meiduo.settings import dev

import logging

from oauth.models import OAuthQQUser
from oauth.utils import generte_access_token, check_access_token
from users.models import User

logger = logging.getLogger('django')
# qq登陆网址
class QQURLView(View):
    def get(self,request):
        next = request.GET.get('next')
        oauth = OAuthQQ(client_id=dev.QQ_CLIENT_ID,
                        client_secret=dev.QQ_CLIENT_SECRET,
                        redirect_uri=dev.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()

        return JsonResponse({'code':0,
                             'errmsg':'ok',
                             'login_url':login_url})


class QQURLSecondView(View):

    def get(self,request):
        # 获取openid
        code =request.GET.get('code')
        if not code:
            return JsonResponse({'code':400,
                                 'errmsg':'缺少code'})
        oauth = OAuthQQ(client_id=dev.QQ_CLIENT_ID,
                        client_secret=dev.QQ_CLIENT_SECRET,
                        redirect_uri=dev.QQ_REDIRECT_URI,
                        )
        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)

        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':400,
                                 'errmsg':'oauth2.0认证失败, 即获取qq信息失败'})
# 判断openid是否绑定

        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            access_token = generte_access_token(openid)
            return JsonResponse({'code': 300,
                                 'errmsg': 'ok',
                                 'access_token': access_token})
        else:
            user = oauth_qq.user
            login(request,user)

            response = JsonResponse({'code':0,
                                     'errmsg':'ok'})
            response.set_cookie('username',
                                user.username,
                                max_age=3600*24*14)
            return response

    #     openid绑定
    def post(self, request):
        '''qq登录的第三个接口'''

        # 1.接收参数(json)
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')
        sms_code_client = dict.get('sms_code')
        access_token = dict.get('access_token')

        # 2.总体检验,查看是否为空
        if not all([mobile, password, sms_code_client, access_token]):
            return JsonResponse({'code':400,
                                 'errmsg':'缺少必传参数'})

        # 3.mobile单个检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': 'mobile格式有误'})

        # 4.password单个检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'errmsg': 'password格式有误'})


        # 5.链接redis, 获取redis的链接对象
        redis_conn = get_redis_connection('verify_code')

        # 6.从redis中获取服务端的短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 7.判断服务端的短信验证码是否过期
        if not sms_code_server:
            return JsonResponse({'code': 400,
                                 'errmsg': '短信验证码过期'})

        # 8.对比前后端的短信验证码
        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 400,
                                 'errmsg': '输入的短信验证码有误'})

        # 9.自定义一个函数,把access_token解密:openid
        openid = check_access_token(access_token)

        # 10.判断openid是否存在,如果存在没问题
        if openid is None:
            return JsonResponse({'code': 400,
                                 'errmsg': 'openid为空'})

        try:
            # 11.从User表中获取一个该手机号对应的用户
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 12.如果该用户不存在, 给User增加一个新的记录
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        else:
            # 13.如果该用户存在, 比较密码是否一致
            if not user.check_password(password):
                return JsonResponse({'code': 400,
                                 'errmsg': '密码输入的不对'})


        # 14.把openid和user保存到QQ表中
        try:
            OAuthQQUser.objects.create(openid=openid,
                                       user=user)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '保存到qq表中出错'})

        # 15.状态保持
        login(request, user)


        response = JsonResponse({'code':0,
                                 'errmsg':'ok'})

        # 16.设置cookie:username
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # # 17.返回json
        # # 增加合并购物车功能:
        # response = merge_cookie_to_redis(request, response)


        # 12.返回结果(json)
        return response
